<template>
  <div style="height: calc(100vh - 80px)">
    <!--地图Div-->
    <div class="map-display" id="mapDiv"></div>
    <!--地图左上角按钮栏-->
    <div id="myToolBtns" class="mytool-btns">
      <div id="buttonDiv" style="float: left;">
        <div class="navbtn-items" v-if=layerShow @click="togglePanel('lyrPanelVisible','layerFlag')" title="图层" id="layerBtn">
          <img src="../../assets/images/map_icons/layer.png">
          <img v-show="layerFlag" src="../../assets/images/map_icons/selectPoint.png"
               class="item-selected">
        </div>
        <div class="navbtn-items" v-if=legendShow @click="togglePanel('legendDivVisible','legendFlag')" title="图例" id="legendBtn">
          <img src="../../assets/images/map_icons/legend.png">
          <img v-show="legendFlag" src="../../assets/images/map_icons/selectPoint.png"
               class="item-selected">
        </div>
        <div class="navbtn-items" v-if=measureShow @click="togglePanel('measurePanelVisible','measureFlag')" title="测量" id="measureBtn">
          <img src="../../assets/images/map_icons/measure.png">
          <img v-show="measureFlag" src="../../assets/images/map_icons/selectPoint.png"
               class="item-selected">
        </div>
        <div class="navbtn-items" v-if=hawkEyeShow @click="togglePanel('hawkeyePanelVisible','hawkeyeFlag')" title="鹰眼" id="hawkeyeBtn">
          <img src="../../assets/images/map_icons/hawkeye.png">
          <img v-show="hawkeyeFlag" src="../../assets/images/map_icons/selectPoint.png"
               class="item-selected">
        </div>
        <div class="navbtn-items" v-if=decorateShow @click="togglePanel('decoratePanelVisible','decorateFlag')" title="鹰眼" id="decorateBtn">
          <img src="../../assets/images/map_icons/Decorate.png">
          <img v-show="decorateFlag" src="../../assets/images/map_icons/selectPoint.png"
               class="item-selected">
        </div>
        <!--<div class="navbtn-items" v-if=juanlianShow @click="togglePanel('juanlianPanelVisible','juanlianFlag')" title="卷帘对比" id="compareBtn">
          <img src="../../assets/images/map_icons/compare.png">
          <img v-show="juanlianFlag" src="../../assets/images/map_icons/selectPoint.png"
               class="item-selected">
        </div>-->
        <!--<div class="navbtn-items" @click="togglePanel('ftTreeSelectVisible','regionFlag')" title="区域选择" id="regionBtn">
          <img src="../../assets/images/map_icons/location.png">
          <img v-show="regionFlag" src="../../assets/images/map_icons/selectPoint.png"
               class="item-selected">
        </div>-->

      </div>
    </div>

    <!--图层管理面板-->
    <div class="layerBox" :class="{'layer-hide':lyrPanelVisible}" :id="lyrBox">
      <div id="panelHeader">
        <div class="options lyropt">
          <span style="font-weight: bold;font-size: 1.2em;">图层管理面板</span>
          <el-checkbox @change="handleOpt" style="color: black; float: right;">图层透明度调节</el-checkbox>
        </div>
      </div>
    </div>

    <!--“量测”下拉-->
    <div class="mapMeasurementTools" :class="{'layer-hide':measurePanelVisible}">    <!--tool-item-panel v-if="measurePanelVisible"-->
      <div class="map-tool-item" title="测面积" @click="myMeasureArea">  <!--@click="triggerBus('area')"-->
        <img src="../../assets/images/map_icons/Area.png" />
        <span>面积</span>
      </div>
      <div class="map-tool-item" title="测距离" @click="myMeasureDistance">    <!--@click="triggerBus('distance')"-->
        <img src="../../assets/images/map_icons/Distance.png" />
        <span>距离</span>
      </div>
      <div class="map-tool-item" title="清除量测结果" @click="myClearMeasure">  <!-- @click="triggerBus('clean')"-->
        <img src="../../assets/images/map_icons/清空.svg" />
        <span>清除</span>
      </div>
    </div>

    <!--“整饰”下拉-->
    <div class="tool-item-panel mapDecorateTools" id="mapDecorateTools" :class="{'layer-hide':decoratePanelVisible}" data-toolPanel-title="Decorate">
      <div class="map-tool-item"  id="CoordinateDisplay" title="坐标" @click="coordinateShow=!coordinateShow">
        <img src="../../assets/images/map_icons/Coordinate.png">
        <span>坐标</span>
      </div>
      <div class="map-tool-item"  id="ScaleDisplay" title="比例尺" @click="scaleShow=!scaleShow">
        <img src="../../assets/images/map_icons/Scale.png">
        <span>比例尺</span>
      </div>
      <div class="map-tool-item"  id="LegendDisplay" title="图例">
        <img src="../../assets/images/map_icons/legend_menuItem.png">
        <span>图例</span>
      </div>
      <!--<div class="map-tool-item"  id="GraticuleDisplay" title="经纬网格">
          <img src="../../dist/mapctrl/mcicons/Legend.png">
          <span>经纬网格</span>
      </div>-->
      <!--<div class="map-tool-item"  id="styleChange" title="调整矢量图层标签等样式">
        <img src="../../dist/img/navbtn/样式.png">
        <span>矢量标签</span>
      </div>-->
    </div>

    <!--坐标与比例尺-->
    <div class="coordinateAndScaleBar">
      <!--地图比例尺-->
      <div id="scaleBarDiv" class="map-scalebar" v-show="scaleShow">
        <div id="scaleBar"></div>
      </div>
      <!--地图坐标 (id必须为mouse-position，否则无法正常显示)-->
      <div class="map-decorate map-coordinate custom-mouse-position" id="mouse-position" v-show="coordinateShow"></div>
    </div>

  </div>
</template>

<script>
  //import {bus} from '../../bus.js'   //引入bus.js定义的空的Vue实例
  import 'ol/ol.css';
  import 'ol-ext/dist/ol-ext.css';
  import {Map,View,Overlay} from 'ol';
  import Popup from 'ol-ext/overlay/Popup'
  import { Tile, Group, Image, Vector as lVector, VectorTile as lVectorTile } from 'ol/layer'
  import {XYZ, Vector} from 'ol/source'
  import { fromLonLat,   toLonLat, get as projGet, getPointResolution } from 'ol/proj'
  import Draw from 'ol/interaction/Draw'
  import { GeoJSON } from 'ol/format'
  import { Style, Fill, Stroke, Circle, Text, Circle as CircleStyle } from 'ol/style'
  import {defaults, Attribution, Zoom, ZoomSlider, OverviewMap, ScaleLine, MousePosition} from 'ol/control';
  import { createStringXY } from 'ol/coordinate'
  import { Logo, TileSuperMapRest, Tianditu, MeasureService, QueryService } from '@supermap/iclient-ol';
  import LayerSwitcher from 'ol-ext/control/LayerSwitcher'

  export default {
    name:'MyMap',
    components: {
    },
    props: {
      mapCtrlTools:{
        type:Array,
        default:function () {
          return []
        }
      },
      lyrdata: {
        type: Array,
        default: []
      },
      mapParams: {
        type: Object,
        default: {}
      },
      spatialQueryConditions: {
        type: Array,
        //default: {}  //若这样设置，当父组件不往子组件传值或传空值的时候，将导致后续有forEach报错
        default: function () {  //设置成这样后，即使父组件不传值也不会造成影响
          return []
        }
      },
      pn: {  //parent_name的简称，即告诉此子组件，当前访问的父组件是谁，以便响应不同的业务逻辑
        type: String,
        default: function () {  //设置成这样后，即使父组件不传值也不会造成影响
          return ''
        }
      },
    },
    data () {
        return {
          /**地图各悬浮面板的可视状态**/
          lyrPanelVisible:true,  //默认true为隐藏
              legendDivVisible:true,  //默认true为隐藏
          measurePanelVisible:true, //默认true为隐藏
          decoratePanelVisible:true, //默认true为隐藏

          hawkeyePanelVisible:true, //默认true为隐藏
          orderLayerDialogVisible:true,  //默认true为隐藏
          newLayerDialogVisible:true,  //默认true为隐藏
          juanlianPanelVisible:true,  //默认true为隐藏
          ftTreeSelectVisible:true,  //默认true为隐藏
          coordinateShow: true, //2D坐标,默认false不显示
          scaleShow: true, //显示比例尺,默认false不显示
          /**地图左上角-功能启动图标按钮-初始化控制**/
          layerShow:false,//图层控制-功能启动图标按钮，默认false不显示
          legendShow:false,//图例-功能启动图标按钮，默认false不显示
          measureShow:false,//测量工具-功能启动图标按钮，默认false不显示
          hawkEyeShow:false,//鹰眼-功能启动图标按钮，默认false不显示
          decorateShow:false,//鹰眼-功能启动图标按钮，默认false不显示
          juanlianShow:false,//卷帘-功能启动图标按钮，默认false不显示
          regionShow:false,//区域选择树-功能启动图标按钮，默认false不显示
          attrTableShow:false,//属性表格-功能启动图标按钮，默认false不显示
          mapQueryShow:false,//地图查询-功能启动图标按钮，默认false不显示
          modelBuildingShow:false,//模型构建与空间分析-功能启动图标按钮，默认false不显示
          statisticalAnalysisShow:false,//统计分析-功能启动图标按钮，默认false不显示

          layerFlag: false, //图层选中显示红色小标志，默认false为隐藏
          legendFlag: false, //图例选中显示红色小标志，默认false为隐藏
          measureFlag:false, //测量选中显示红色小标志，默认false为隐藏
          hawkeyeFlag:false, //鹰眼选中显示红色小标志，默认false为隐藏
          decorateFlag:false, //鹰眼选中显示红色小标志，默认false为隐藏
          juanlianFlag:false, //卷帘选中显示红色小标志，默认false为隐藏
          regionFlag:false, //区域选中显示红色小标志，默认false为隐藏
          dtcxFlag:false, //地图查询选中显示红色小标志，默认false为隐藏
          attrTableFlag:true, //属性表格选中显示红色小标志，默认为true显示
          modelFlag:false, //属性表格选中显示红色小标志，默认false为隐藏

          measureUrl:"https://iserver.supermap.io/iserver/services/map-world/rest/maps/World?prjCoordSys=%7B%22epsgCode%22:3857%7D",
          measureVectorLayer:null,
          measureInteraction:null,
          measureSource:null,
          measureFeature:null

        }
    },
    methods:{
      togglePanel(attr,attr2){
        this[attr] = !this[attr];
        this[attr2] = !this[attr2];
      },
      initMyMap1(){

        let that = this;//以便在整个initMyMap方法体中的所有嵌套函数都能拿到thisVue

        //region定义Map和View
        var map = new Map({
          target: 'mapDiv',
          controls: defaults({attribution: false, zoom: false, rotate: false}), //默认取消ol自带的控件显示
          //controls: control.defaults({attributionOptions: {collapsed: false}}).extend([new Logo()]),
          view: new View({
            projection: this.mapParams.projection, //例如：'EPSG:4326', //发布的影像原始坐标系为4326，必须加上此投影才能显示发布的影像
            center: fromLonLat(this.mapParams.center), //例如：[127.87535, 43.58279] 或 [126.47535, 43.58279],//地图初始中心点
            minZoom: this.mapParams.minZoom, //例如：5，//可以缩小的最小级别;若为undefined表示无限制
            maxZoom: this.mapParams.maxZoom, //例如：19，//可以放大的最大级别；若为undefined表示无限制
            zoom: this.mapParams.zoom, //例如：6，//地图初始化时显示级别；注意：若此处未定义，地图初始化显示不出来
            //mExtent:this.mapParams.mExtent, //左下点-右上点
          })
        });
        this.map = map;//把地图传出去，以便外面调用
        //endregion

        //region自定义加载图层
        let lyrdata = this.lyrdata;
          //console.log(lyrdata,333333333);
        this.baseMap = []
        for (let i = 0, len = lyrdata.length; i < len; i++) {
            //console.log(lyrdata[i],555)
          let tmpLyrs = this.addLayerAtInit(lyrdata[i]);
          tmpLyrs.forEach(value => {
            this.baseMap.push(value);
            this.map.addLayer(value);

            //添加图例
            /*if (value instanceof Group) {
              value.values_.layers.forEach(l => {
                if (l.getVisible()) {
                  this.addLegend(l);
                }
              })
            } else {
              if (value.getVisible()) {
                this.addLegend(value);
              }
            }*/

          }) //end fo forEach
        } //end of for
        //endregion

        //region手动测试加载图层
        // 加载天地图图层
        function addTdtLayer (type) {
          let layer = new Tile({
            source: new XYZ({
              url: 'http://t' + Math.round(Math.random() * 7) + '.tianditu.com/DataServer?T=' + type + '&tk=cc8b1a46f82b9042ceb3773a900a2a0a&x={x}&y={y}&l={z}',
              projection: 'EPSG:3857'
            })
          })
          layer.id = type
          return layer
        }
        // 添加天地图
        function addTdt() {
          map.addLayer(addTdtLayer('img_w')) // 天地图影像地图
          map.addLayer(addTdtLayer('cia_w')) // 天地图影像标注图层
        }
        //addTdt();

        let tdtLayer_ter = new Tile({
          source: new Tianditu({
            layerType: 'ter',//地形图
            key:'cc8b1a46f82b9042ceb3773a900a2a0a',
            projection: "EPSG:3857"
          })
        });
        //map.addLayer(tdtLayer_ter);

        let tdtLayer_cta = new Tile({
          source: new Tianditu({
            layerType: 'cta',//地形图注记
            key:'cc8b1a46f82b9042ceb3773a900a2a0a',
            projection: "EPSG:3857"
          })
        });
        //map.addLayer(tdtLayer_cta);

        //例子：添加TileSuperMapRest类型的图层
        var layer4KJ = new Tile({
          title:"GanNanDiLiWeiZhi", //如果不加这个title属性，则图层管理面板就显示空白条目了
          source: new TileSuperMapRest({
            url: 'http://jlu3s.com:7030/iserver/services/map-GanNanDiLiWeiZhi/rest/maps/%E8%B5%A3%E5%8D%97%E8%A1%8C%E6%94%BF%E4%BA%A4%E9%80%9A%E5%92%8C%E5%9C%B0%E5%BD%A2',
            wrapX: true
          }),
          projection: 'EPSG:3857'
        });
        //map.addLayer(layer4KJ);
        //endregion

        //region地图版权控件
          let attrCtl = new Attribution({collapsed: true}); //true表示默认收缩
          map.addControl(attrCtl);
        //endregion

        //region缩放控件
          //zoom控件
          let myZoomControl = new Zoom();
          map.addControl(myZoomControl);

          //zoomBar控件
          let myZoomSlider = new ZoomSlider({})
          map.addControl(myZoomSlider);
        //endregion

        //region比例尺和坐标
          //let myScaleControl = new control.ScaleLine();
          //map.addControl(myScaleControl);
          let scaleLineControl = new ScaleLine({
            units: 'metric',
            target: 'scaleBar',
            className: 'ol-scale-line'
          })
          this.map.addControl(scaleLineControl);
          //添加坐标
          let mousePositionControl = new MousePosition({
            coordinateFormat: createStringXY(5), //坐标小数位数
            className: 'custom-mouse-position',
            target: document.getElementById('mouse-position'),
            undefinedHTML: '&nbsp;',
            projection: 'EPSG:4326'
          })
          this.map.addControl(mousePositionControl);
        //endregion

        //region图层切换控件
          //let myLayerSwitcher = new control.LayerSwitcher({});
          //map.addControl(myLayerSwitcher);
        //endregion

        //region鹰眼快视控件【底图怎么办？？】
          let myOverviewMap = new OverviewMap({
              view: new View({
                projection: 'EPSG:3857',
                multiWorld: true
              }),
              collapsed: true, //true为默认折叠
              layers: [ addTdtLayer('img_w') ]
            })
          map.addControl(myOverviewMap);
        //endregion

        //region图层管理控件
        if (!document.body.classList.contains('hideOpacity')) {
          document.body.classList.add('hideOpacity')
          document.body.classList.add('hidePercent')
        }

        let lyrs = [];
        /*this.baseMap.forEach(layer => {
          if (!(layer instanceof Group && layer.values_.title === '天地图服务')) {
            lyrs.push(layer);
          }
        })*/
        //let lyrsForLayerSwitcher = new Group({ layers: lyrs })
        let switcher = new LayerSwitcher({
          target: document.querySelector('#' + this.lyrBox),
          show_progress: true, //在切片图层上显示进度条，默认为false
          reordering: true, //允许图层重新排序，默认值为true
          trash: false, //添加垃圾桶按钮以删除图层，默认为false
          extent: true, //添加范围按钮以缩放到图层范围
          //layerGroup: lyrsForLayerSwitcher //筛选出要显示的图层？？
        })
        //通过这种方式覆盖了LayerSwitcher.js源代码中的ol_control_LayerSwitcher.prototype.tip
        //从而重新定义了title提示信息
        switcher.tip = {
          up: '上下移动改变图层叠加顺序[up/down]',
          down: '往下[down]',
          info: '图层相关信息说明[informations...]',
          extent: '跳转到该图层最大范围[zoom to extent]',
          trash: '移除该图层[remove layer]',
          plus: '展开/收缩图层组[expand/shrink]'
        }
        map.addControl(switcher)
        //endregion 图层管理控件

        //region地图SQL查询并渲染在地图上
        /*var layer = new Tile({
         title:"赣南土特产",
         source: new TileSuperMapRest({
         url: "http://jlu3s.com:7030/iserver/services/map-GanNanKeJiaTuTeChan/rest/maps/%E8%B5%A3%E5%8D%97%E5%AE%A2%E5%AE%B6%E5%9C%9F%E7%89%B9%E4%BA%A7%E5%9B%BE?prjCoordSys=%7B%22epsgCode%22:3857%7D"
         }),
         projection: 'EPSG:3857'
         //projection: 'EPSG:4326'
         });
         this.map.addLayer(layer);*/

        /*let myQueryConditions ={
         queryUrl:this.spatialQueryConditions.queryUrl,
         layerName:this.spatialQueryConditions.layerName,
         attributeFilter:this.spatialQueryConditions.attributeFilter,
         dataProjection:this.spatialQueryConditions.dataProjection,
         featureProjection:this.spatialQueryConditions.featureProjection
         };
         console.log(myQueryConditions,"myQueryConditions");
         if(myQueryConditions.queryUrl && myQueryConditions.layerName){
         console.log("满足条件，可以查询");
         MyQueryBySQLConditions(myQueryConditions);//调用查询
         }*/
        if(this.spatialQueryConditions){
          console.log("this.spatialQueryConditions有值")
          this.spatialQueryConditions.forEach(item=>{
            console.log(item,"this.spatialQueryConditions",777)
            if(item.queryUrl && item.layerName){
              //console.log("满足条件，可以查询");
              MyQueryBySQLConditions(item);//调用查询
            }
          });
        }else{
          console.log("本页面尚未配置spatialQueryConditions……")
        }

        function MyQueryBySQLConditions({queryUrl,layerName,attributeFilter,dataProjection,featureProjection}){
          //要查询的服务地址
          //let queryUrl = "http://jlu3s.com:7030/iserver/services/map-GanNanKeJiaTuTeChan/rest/maps/%E8%B5%A3%E5%8D%97%E5%AE%A2%E5%AE%B6%E5%9C%9F%E7%89%B9%E4%BA%A7%E5%9B%BE?prjCoordSys=%7B%22epsgCode%22:3857%7D";
          //let queryUrl = this.MYCONFIG.spatialQueryConditions.queryUrl;
          //设置查询条件
          var param = new SuperMap.QueryBySQLParameters({
            queryParams: {
              //name: "土特产@土特产",
              //name: this.MYCONFIG.spatialQueryConditions.layerName,
              name: layerName,
              //attributeFilter: "SmUserID=0"
              //attributeFilter:this.MYCONFIG.spatialQueryConditions.attributeFilter
              attributeFilter:attributeFilter
            }
          });
          //执行SQL查询
          new QueryService(queryUrl).queryBySQL(param, function (serviceResult) {
            //console.log(serviceResult.result.recordsets[0].features,777666)
            /*let r_features = serviceResult.result.recordsets[0].features;
             console.log(r_features,777666)*/
            //console.log(fromLonLat(r_features),666555)
            //console.log(serviceResult.result.recordsets[0].features.attributes,666555)
            //console.log(serviceResult.result.recordsets[0].features.attributes.lonLat,666555444333)
            var vectorSource = new Vector({
              features: (new GeoJSON()).readFeatures(serviceResult.result.recordsets[0].features,{   //终于发现可以通过在这里设置参数把查询结果从4326转到与地图视图相一致的3857坐标系了
                /*dataProjection: 'EPSG:3857',
                 featureProjection:'EPSG:3857'*/
                dataProjection: dataProjection,
                featureProjection:featureProjection
              }),
              //features: serviceResult.result.recordsets[0].features, //注意：不经过GeoJson转换的好像不能识别
              wrapX: false
            });
            //新建矢量图层存放结果
            var resultLayer = new lVector({
              title:"查询结果",
              //projection: 'EPSG:4326',
              //projection: 'EPSG:3857',
              source: vectorSource
              //,style: new Style({ fill: new Fill({ color: 'rgba(223, 216, 212, 0.1)' }), stroke: new Stroke({ color: 'rgba(0, 153, 255, 1)', width: 2 }) })
            });
            //将结果添加到地图上
            map.addLayer(resultLayer);
          });
        }
        //endregion

        //region信息窗口相关
        let popup = new Popup (
          {	popupClass: "default", //"tooltips", "warning" "black" "default", "tips", "shadow","anim"
            closeBox: true,
            onshow: function(){ console.log("You opened the box"); },
            onclose: function(){ console.log("You close the box"); },
            positioning: 'auto',
            autoPan: true,
            autoPanAnimation: { duration: 750 }
          });
        map.addOverlay(popup); //一定要加到地图上，否则不显示

        let featurePics = this.MYCONFIG.featurePics;
        let spatialQueryConditions = this.spatialQueryConditions;
        console.log("spatialQueryConditions:",spatialQueryConditions,676)

        function getHtml(features) {
          //创建属性框
          let html = '';
          html += `<div class="ol-popupfeature">`;
          //html += `<i class="ol-fix"></i>`
          html += `<table>`;
          html += `<tr><th>属性名称</th><th>属性值</th></tr>`;

          let f = features;
          //遍历各属性字段信息并放置到表格中
          for (const key in f.values_) {
            if (f.values_.hasOwnProperty(key)
              && key != 'geometry'
              && key != 'SmID'
              && key != 'SmUserID'
              && key != 'the_geom'
              && key != 'PopupInfo'
              && key != 'imgSrc'
            ) {
              const element = f.values_[key];
              if (element) {
                html += `<tr><td>${key}</td><td>${element}</td></tr>`;
              }
            }
          }

          //检测是否含有图片，若有则输出为html格式内容以便后续插入信息窗口中
          let picsDiv;
          //根据imgSrc属性字段的值来获取相关图片地址
          let imgSrcStr = f.values_["imgSrc"];
          if(imgSrcStr){
            console.log("→优先使用方法1：属性直接读取图片地址法!!")
            let imgSrcArr = imgSrcStr.split('**');
            picsDiv = buildPicDivForFeature(imgSrcArr);
          }else if(spatialQueryConditions){
            console.log("→使用方法2：配置信息读取图片地址法")
            picsDiv = getPicsDivFromSpatialQueryConditions(f);
          }
          //如果有图片则把图片罗列出来
          if(picsDiv){
            html += picsDiv;
          }
          html += `</table>`;
          //html += `<button type="button" class="ol-zoombt"></button>`;
          html += `</div>`;
          return html;
        } //end of getHtml()

        //（方法1）根据某要素图形所含的图片地址数组构建图片Div
        function buildPicDivForFeature(imgSrcArr){
          let picsDiv = "";
          imgSrcArr.forEach(item => {
            if(item){
              picsDiv += "<a href='" + item + "' target='_blank' style='display:inline-block;margin:10px;'><img src='" + item + "' width='120px;' height='90px;'></a>";//picsDiv += "<a href='" + arr + "' target='_blank' style='display:inline-block;margin:10px;'><img src='" + arr + "' width='120px;' height='90px;'></a>";
              //picsDiv += "<a onclick=\"xadmin.open('实地照片','" + arr + "',1200,'')\" style='display:inline-block;margin:10px;'><img src='" + arr + "' width='120px;' height='90px;'></a>";//picsDiv += "<a href='" + arr + "' target='_blank' style='display:inline-block;margin:10px;'><img src='" + arr + "' width='120px;' height='90px;'></a>";
            }
          });
          picsDiv = "<tr>" +
            "<td  colspan='2'>" + picsDiv + "</td>" +
            "</tr>";
          return picsDiv;
        }

        //（方法2）根据SpatialQueryConditions来构建图片Div
        function getPicsDivFromSpatialQueryConditions(features){
          let myPicsDiv;
          spatialQueryConditions.forEach(item=>{
            console.log("spatialQueryConditions的值为",item,8764321)
            if(item.keyField){
              myPicsDiv = whichFeatureHasPics(features.values_.SmID,features.values_[item.keyField]); //此处前面要承接picsDiv,否则图片出不来
            }
          });
          return myPicsDiv;
        }

        function whichFeatureHasPics(ags1,ags2){
          //console.log(ags1,ags2,333333335555555)
          let picsDiv = "";
          /*注意，这里的featurePics输入全局变量引入了*/
          featurePics.forEach(item => {
            if (item[0] == ags1 && item[1] == ags2 ) { //经过测试，此处暂时不能用===恒等
              //console.log(item,333999)
              item[2].forEach(arr => {
                picsDiv += "<a href='" + arr + "' target='_blank' style='display:inline-block;margin:10px;'><img src='" + arr + "' width='120px;' height='90px;'></a>";//picsDiv += "<a href='" + arr + "' target='_blank' style='display:inline-block;margin:10px;'><img src='" + arr + "' width='120px;' height='90px;'></a>";
                //picsDiv += "<a onclick=\"xadmin.open('实地照片','" + arr + "',1200,'')\" style='display:inline-block;margin:10px;'><img src='" + arr + "' width='120px;' height='90px;'></a>";//picsDiv += "<a href='" + arr + "' target='_blank' style='display:inline-block;margin:10px;'><img src='" + arr + "' width='120px;' height='90px;'></a>";
                //console.log(picsDiv,"picsDiv");
              });
            }
          });
          picsDiv = "<tr>" +
            "<td  colspan='2'>" + picsDiv + "</td>" +
            "</tr>";
          //console.log(picsDiv,"包含了<tr><td>的picsDiv");
          return picsDiv;
        }

        //移除信息窗口
        function removePopup() {
          popup.setPosition(undefined);
          //closer.blur();
        }
        //图层信息框内容更新
        function updateInfoView(feature) {
          if (!feature && popup) {
            removePopup();
            return;
          }
          if(feature){
            let html = getHtml(feature);
            //highLightVector.addFeatures(feature);
            //highLightLayer.addFeatures(feature);
            //console.log(highLightLayer,321)
            popup.show(feature.getGeometry().getCoordinates(), html);
          }

        } //end of updateInfoView()


        //console.log(that.pn,998877)
        //if(JSON.stringify(this.pn) == "{}"){console.log("no,pn")} else if(this.pn){console.log("yes,pn")}
        //let myPN=that.pn;
        let sqcArr = that.MYCONFIG.spatialQueryConditions[that.pn]; //有值，或undefined
        console.log(sqcArr,"that.MYCONFIG.spatialQueryConditions[that.pn]",86543);
        if(sqcArr){
          sqcArr.forEach(item=>{
            console.log(item.mouseEventType,556677)
            /*if(item.mouseEventType == 'click'){
             console.log("click!!!!!!!!!!!!!")
             map.on('click', mouseEventLinstener);
             return;
             }
             if(item.mouseEventType == 'pointermove'){
             console.log("pointermove!!!!!!!!!!!!!")
             map.on('pointermove', mouseEventLinstener);
             return;
             }*/
            map.on(item.mouseEventType, mouseEventLinstener);

          });
        }

        //（监听）地图单击、双击、悬浮等的全局事件
        //map.on('click', mouseEventLinstener);  //map.on('pointermove', pointermoveLinstener);
        function mouseEventLinstener(e) {
          map.forEachFeatureAtPixel(e.pixel, function (feature,layer) {
            updateInfoView(feature);
          });
        }
        //endregion

      },
      addLayerAtInit({lyrType,srcType,mUrl,mTitle,mName,mVisible,mSubLayers}){
        let that = this;
        let lyrArr = []
        let lyr = null
        if (lyrType === 'Tile' && srcType === 'TileSuperMapRest') {
          lyr = new Tile({
            title: mTitle,
            name: mName,
            visible: mVisible,
            //key: mKey,
            //layersForLegend: layerParams.layersForLegend,
            //productDate: mProductDate,
            projection: 'EPSG:3857',
            source: new TileSuperMapRest({
              url: mUrl,
              wrapX: true
            })
          })
          lyrArr.push(lyr)
        } else if (lyrType === 'Tile' && srcType === 'XYZ'){
            if (mTitle === "路网" || mTitle === "卫星" || mTitle === "文字标注") {
              lyr = new Tile({
                title: mTitle,
                name: mName,
                visible: mVisible,
                source: new XYZ({
                  url: mUrl,
                })
              })
            }
          lyrArr.push(lyr)
        } else if (lyrType === 'Group') {
          let lG = []
          for (let i = 0; i < mSubLayers.length; i++) {
            let lyr4tmps = null
            lyr4tmps = that.addLayerAtInit(mSubLayers[i])
            lyr4tmps.forEach(value => {
              lG.push(value)
            })
          }
          lyr = new Group({
            title: mTitle,
            visible: mVisible,
            layers: lG
          })
          lyrArr.push(lyr)
        } else {
          console.log(lyrType,srcType,mUrl,mTitle,'抱歉，地图资源类型不明，请检查并重试，或联系管理员协助解决。')
        }
        return lyrArr
      },

      //region地图量测（面积）
      myMeasureArea(){
        let that = this;
        that.myClearMeasure();//先清除先前的图形以避免干扰
        //let url = "https://iserver.supermap.io/iserver/services/map-world/rest/maps/World";
        //let url = "https://iserver.supermap.io/iserver/services/map-world/rest/maps/World?prjCoordSys=%7B%22epsgCode%22:3857%7D";
        let vectorLayer, interaction, source,feature;
        source = new Vector({wrapX: false});
        vectorLayer = new lVector({
          title:"测面积overlay图层",
          source: source
        });
        this.map.addLayer(vectorLayer);
        this.measureVectorLayer=vectorLayer;

        interaction = new Draw({
          source: source,
          type: "Polygon",
        });

          this.measureInteraction = interaction;//传出去以便后续集中清理掉
        this.map.addInteraction(interaction);

        interaction.on('drawstart', function (evt) {
          feature = evt.feature;
        });
        interaction.on('drawend', function () {
          var areaMeasureParam = new SuperMap.MeasureParameters(feature.getGeometry());
          //console.log(areaMeasureParam,7777777)
          new MeasureService(that.measureUrl).measureArea(areaMeasureParam, function (serviceResult) {
            console.log(serviceResult.result.area, serviceResult.result.unit);
            alert(serviceResult.result.area+" 平方米");
            //widgets.alert.showAlert(serviceResult.result.area + resources.msg_sqm, true);
          });
        });
      },
      //endregion
      //region地图量测（距离）
      myMeasureDistance(){
        let that = this;
        this.myClearMeasure();//先清除先前的图形以避免干扰
        //let url = "https://iserver.supermap.io/iserver/services/map-world/rest/maps/World";
        //let url = "https://iserver.supermap.io/iserver/services/map-world/rest/maps/World?prjCoordSys=%7B%22epsgCode%22:3857%7D";
        let vectorLayer, interaction, source,feature;
        source = new Vector({wrapX: false});
        vectorLayer = new lVector({
          title:"测距离overlay图层",
          source: source
        });
        this.map.addLayer(vectorLayer);
        this.measureVectorLayer=vectorLayer;

        interaction = new Draw({
          source: source,
          type: "LineString",
        });

          this.measureInteraction = interaction;//传出去以便后续集中清理掉
        this.map.addInteraction(interaction);

        interaction.on('drawstart', function (evt) {
          feature = evt.feature;
        });
        interaction.on('drawend', function () {
          var areaMeasureParam = new SuperMap.MeasureParameters(feature.getGeometry());
          //console.log(areaMeasureParam,7777777)
          new MeasureService(that.measureUrl).measureArea(areaMeasureParam, function (serviceResult) {
            console.log(serviceResult.result.area, serviceResult.result.unit);
            alert(serviceResult.result.area+" 米");
            //widgets.alert.showAlert(serviceResult.result.area + resources.msg_sqm, true);
          });
        });
      },
      //endregion
      //region地图量测（清除）
      myClearMeasure(){
        let that = this;
        that.map.removeLayer(that.measureVectorLayer);//清除图形
        that.map.removeInteraction(that.measureInteraction) //移除绘制图形的交互动作
        /*if (draw) {
          draw.setActive(false) //取消激活状态，以便退出绘制
        }*/
        let ols = that.map.getOverlays();
        console.log(ols,333777)
        ols.clear() //把所有覆盖物（测量结果）都清楚掉
        //that.map.removeLayer(that.drawVector) //把vector图层也清除掉，从而清除测量图形
        //注：此处不能通过var定义局部变量，会导致全局vector调用局部source而报错
        //that.drawSource = null //先清空全局变量source
        //that.drawSource = new Vector() //再实例化一个矢量图层给全局变量source，从而消除上次测量残留
        //that.drawVector.setSource(that.drawSource) //更新vector的新源，避免本次量测残留图形对后续新量测的影响
      },
      //endregion

      //透明度调节
      handleOpt() {
        document.body.classList.toggle('hideOpacity')
        document.body.classList.toggle('hidePercent')
      },

      //地图中的面板可拖动
      dragFunc(id) {
        var Drag = document.getElementById(id);
        Drag.onmousedown = function(event) {
          var ev = event || window.event;
          event.stopPropagation();
          var disX = ev.clientX - Drag.offsetLeft;
          var disY = ev.clientY - Drag.offsetTop;
          document.onmousemove =
            function(event) {
              var ev = event ||
                window.event;
              Drag.style.left = ev.clientX - disX + "px";
              Drag.style.top = ev.clientY -
                disY + "px";
              Drag.style.cursor = "move";
            };
        };
        Drag.onmouseup = function () {
          document.onmousemove = null;
          this.style.cursor = "default";
        };
      }
    },
    created(){
      //region 地图左上角-功能启动图标按钮-初始化控制
      if(this.mapCtrlTools !== undefined && this.mapCtrlTools.length>0){
        this.mapCtrlTools.forEach(item=>{
          if(item === 1){
            this.layerShow = true; //图层控制-功能启动图标按钮
          }else if(item === 2){
            this.legendShow = true;//图例-功能启动图标按钮
          }else if(item === 3){
            this.measureShow = true;//测量工具-功能启动图标按钮
          }else if(item === 4){
            this.hawkEyeShow = true; //鹰眼-功能启动图标按钮
          }else if(item === 5){
            this.juanlianShow = true; //卷帘-功能启动图标按钮
          }else if(item === 6){
            this.regionShow = true; //区域选择树-功能启动图标按钮
          }else if(item === 7){
            this.mapQueryShow = true; //地图查询-功能启动图标按钮
          }else if(item === 8){
            this.modelBuildingShow = true; //模型构建与空间分析-功能启动图标按钮
          }else if(item === 11){
            this.attrTableShow = true; //属性表格（抽屉）-功能启动图标按钮
          }else if(item === 12){
            this.statisticalAnalysisShow = true; //统计分析（抽屉）-功能启动图标按钮
          }else if(item === 13){
            this.decorateShow = true; //统计分析（抽屉）-功能启动图标按钮
          }
        });
      }
      //endregion
    },
    mounted(){
      /*地图初始化*/
      this.initMyMap1();
      /*让地图中的某些面板可拖动*/
      //this.dragFunc("lyrBox");
      //this.dragFunc(this.lyrBox);
    },
    watch:{},
    computed:{
      lyrBox: function () {
        return 'lyrBoxDiv' + new Date().valueOf()
      }
    }
  }
</script>

<style scoped>

  @import '~ol-ext/dist/ol-ext.css';
  @import '../../assets/styles/my-ol-ext.css';

  .map-display {
    position: absolute;
    width: 100%;
    height:100%;
    background-color: darkgray;
  }

  /*地图工具栏相关样式  */
  .mytool-btns{
    position: relative;
    /*left: 10px;*/
    margin-left:2.5em;
    top: 10px;
    height: 60px;
  }

  .navbtn-items{
    float: left;
    margin: 0 5px;
    /*border-right: 1px solid #788897; !*显示右侧的边框线*!*/
    position: relative;
    width: 40px;
    height: 40px;
    border-radius: 50%;
    background-color: white;
    text-align: center;
  }

  .navBtnDiv{
    /*width: auto;*/
    /*background-color:rgba(0,0,0,0);*/
    margin-left: 55px;
    /*margin-top: 5px;*/
  }
  .navbtn-btn{
    margin-right: 10px;
  }

  .navbtn-items:hover{
    /*background-color: #d0af25;*/
    /*background-color: rgb(255, 253, 73);*/
    cursor: pointer;
  }

  .navbtn-items>img{
    width:36px;
    height:36px;
    padding:5px;
  }
  .item-selected {
    position: absolute;
    /*width: 20px;*/
    /*height: 20px;*/
    /*left: 15px;*/
    width: 25px !important;
    height: 25px !important;
    left: 15px !important;
    bottom: 0;
  }

  .layer-hide {
    display:none;
  }

  /*右侧工具条对应面板*/
  /*工具项：图层管理&ndash;&gt;>对应面板*/
  .layerBox {
    width: 275px;
    padding: 5px;
    background-color: #ffffff;
    border: solid 1px #cecdd2;
    color: black;
    border-radius: 5px;
    /*display: none;*/ /*交由vue变量去控制*/
    position: absolute;
    z-index: 3;
    /* margin: 2px 0 0 5px; */
    /* right: 50px; */
    /*top:50px;*/
    margin-left: 2.5em;
    box-shadow: 4px 4px 10px #888888;
  }

  #panelHeader {
    width: 100%;
    height: 100%;
    border-radius: 5px;
    /* overflow-x: auto; */
  }

  .lyr-panel-title {
    text-align: center;
    font-size: 1.1em;
    line-height: 1.1em;
    display: block;
    font-weight: bold;
    color: white;
    margin: 0.3em;
  }

  .lyropt {
    font-size: 14px;
    margin-left: 10px;
  }



  /*工具栏-（量测-整饰-控制-查询等）下拉框*/
/*  .tool-item-panel{
    !*position: absolute;*!
    position: fixed;
    z-index: 2;
    !*display: none;*!
  }*/
  /*工具栏-（量测-整饰-控制-查询）下拉框-子项*/
  .map-tool-item{
    width: 85px;
    height: 29px;
    border-bottom: 1px solid #b4b4b4;
    cursor: pointer;
  }

  .map-tool-item>img{
    display: block;
    float: left;
    width: 20px;
    height: 20px;
    margin-top: 4px;
    margin-left: 5px;
  }

  .map-tool-item>span{
    display: block;
    float: left;
    width: 50px;
    height: 20px;
    margin-top: 4px;
    margin-left: 2px;
    line-height: 19px;
    text-align: center;
    font-size:12px;
    font-family:微软雅黑;
  }

  .map-tool-item-click{
    /*color: rgb(18,150,219);*/
    color: rgb(255,0,0);
  }
  /*工具项：量测-->>对应下拉面板*/
  .mapMeasurementTools{
    position:relative;

    width: 85px;
    /*min-height: 220px;*/

    /*top:44px;*/
    /*right计算方式：【69*3-（85-69）】*/
    /*right: 191px;*/
    left: 6em;

    background-color: #ffffff;
    box-shadow: 4px 4px 10px #888888;
    z-index: 5; /*高于lyrBox的3*/
  }

  /*工具项：整饰-->>对应下拉面板*/
  .mapDecorateTools{
    position:relative;
    width: 85px;
    left: 10em;
    background-color: #ffffff;
    box-shadow: 4px 4px 10px #888888;
    z-index: 4; /*高于lyrBox的3*/
  }

  /*地图整饰（坐标、比例尺、图例均通用）*/
  .map-decorate {
    position: absolute;
    /*position: fixed;*/
    /*position: relative;*/
    z-index: 2;
    /*display: block;*/
    /*display: none;*/
  }
  /*比例尺位置*/
  /*用于覆盖原生比例尺的样式*/
  .ol-scale-line {
    background: #f39c12;
    border-radius: 4px;
    bottom: 8px;
    left: -20em; /*约等于16px*20=320px*/
    padding: 2px;
    position: absolute;
    height: 26px;
  }
  .map-scalebar{
    position:absolute;
    bottom:6px;
    left:10em;
    /*top:46px;*/
    /*left:200px;*/
    /*left:485px; !*四个按钮*!*/
    /*left:525px; !*五个按钮*!*/
    /*z-index:999;*/
  }
  /*坐标位置*/
  .map-coordinate{
    /*position:absolute;*/
    /*left:200px;*/
    left:315px;
    /*right:105px;*/
    bottom:15px;
    /*top:10px;*/
    margin:2px 6px;
    padding: 2px 4px;
    font-family:Arial;
    color:#ffffff;
    background-color: #f39c12;
    /*min-width: 150px;*/
    border-radius: 4px;
    height: 20px;
  }



</style>
